package main

import (
	"flag"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jmoiron/sqlx"
	"vip_video/configx"
	"vip_video/controller"
	"vip_video/internal/library"
	"vip_video/middleware"
)

var configPath = flag.String("config_path", "./config.yaml", "配置文件位置")

var DB *sqlx.DB

func main() {
	flag.Parse()

	if err := configx.Init(*configPath); err != nil {
		panic(fmt.Sprintf("解析配置失败:%s", err.Error()))
	}

	//初始化数据库
	db, err := library.InitDB(configx.C.Mysql.Dns)
	if err != nil {
		panic(fmt.Sprintf("连接数据库失败:%s", err.Error()))
	}

	DB = db

	g := gin.Default()

	g.Use(middleware.CorsMiddleware()).Use(middleware.CheckAppMiddleware(DB)).Use(middleware.SafeApiMiddleware())

	{
		testController := controller.NewTestController().WithDb(DB).WithConfig(configx.C)
		testGroup := g.Group("test")
		testGroup.Use(middleware.AuthMiddleware(false, DB, configx.C)).GET("test", testController.Test)
	}

	{
		userController := controller.NewUserController().WithDb(DB).WithConfig(configx.C)
		userGroup := g.Group("user")
		userGroup.POST("mobile_login", userController.MobileLogin)
		userGroup.Use(middleware.AuthMiddleware(true, DB, configx.C)).GET("info", userController.UserInfo)
	}

	{
		swiperController := controller.NewSwiperController().WithDb(DB).WithConfig(configx.C)
		swiperGroup := g.Group("swiper")
		swiperGroup.GET("index", swiperController.Index)
	}

	{
		videoCategoryController := controller.NewVideoCategoryController().WithDb(DB).WithConfig(configx.C)
		videoCategoryGroup := g.Group("video_category")
		videoCategoryGroup.GET("index", videoCategoryController.Index)
	}

	{
		videController := controller.NewVideoController().WithDb(DB).WithConfig(configx.C)
		videoGroup := g.Group("video")
		videoGroup.GET("index", videController.Index)
		videoGroup.GET("detail/:id", videController.Detail)
		videoGroup.GET("channel/:id", videController.Channel)
		videoGroup.GET("chapter/:video_id/:channel_id", videController.Chapter)
		videoGroup.GET("m3u8/:chapter_id", videController.M3u8)

		videoAuthGroup := videoGroup.Group("")
		videoAuthGroup.Use(middleware.AuthMiddleware(true, DB, configx.C)).POST("record/:chapter_id", videController.Record)
		videoAuthGroup.Use(middleware.AuthMiddleware(true, DB, configx.C)).GET("record/:chapter_id", videController.GetRecord)
	}

	if err := g.Run(":9991"); err != nil {
		panic(fmt.Sprintf("启动 http 服务失败:%s", err.Error()))
	}
}
